var collectionList = ['entity','property','impact','threat','countermeasure'];
var rintra = ["is-a"];
//var rinter = ['initiate','deserve','target','dealwith','generate','jeopardize'];
var rinter ={
    entity: ["initiate","deserve"]
    ,property:[]
    ,impact:["jeopardize"]
    ,threat:["target","generate"]
    ,countermeasure:["dealwith","generate"]
}

$(function(){
    var mutex = 0;
    /**
     *  导航栏函数部分
    **/
    /* 显示操作 */
    $("#testTree .element").live("click",function(){
        if(mutex>0){
            mutex--;
        }else{
            //treeItem.getBriefInfo($(this));
            treeItem.getDetailInfo($(this));
        }
    });

    $("#testTree .element").live({
        mouseenter: function(){
            $(this).children("span").show();
        },
        mouseleave: function(){
            $(this).children("span").hide();
        }
    });

    $("#testTree li.nav-header").live({
        mouseenter: function(){
            $(this).children("i").show();
        },
        mouseleave: function(){
            $(this).children("i").hide();
        }
    });


    $("#testTree a.icon").live("click",function(){
        if($(this).hasClass("plus")){
            $(this).removeClass("plus");
            $(this).addClass("minus");
            $(this).parent().children("ul").show();
        }
        else if($(this).hasClass("minus")){
            $(this).removeClass("minus");
            $(this).addClass("plus");
            $(this).parent().children("ul").hide();
        }
    });

    $("#testTree .nav-header .icon-plus-sign").live("click",function(){
        m_element.id = $(this).parent().children("input[type='hidden']").val();
        m_element.type = $(this).parent().text().replace(/(^\s*)|(\s*$)/g, "");

        treeItem.plus($(this).parent());
    });
    /* 三个功能键 */
    $("#testTree span .icon-zoom-in").live("click",function(){
        mutex++;
        treeItem.zoom($(this).parent().parent().parent());
    });

    $("#testTree span .icon-plus").live("click",function(){
        mutex++;
        treeItem.getBriefInfo($(this).parent().parent());
        treeItem.plus($(this).parent().parent().parent());
    });

    $("#testTree span .icon-trash").live("click",function(){
        mutex++;
        treeItem.getBriefInfo($(this).parent().parent());
        treeItem.remove($(this).parent().parent().parent());
    });
});


var treeItem  = {
    zoom : function(item){
        $(item).children("a").trigger("click");
    }
    ,plus: function(item){
        //return $("#modal-create").modal('show');
        var name = window.prompt("Please write the node's name")
        if(name != null && name != ""){
            var data = {
                process : 'add',
                relation : 'is-a',
                source: {
                    id : null,
                    name : name,
                    type : m_element.type
                },
                target : {
                    id : m_element.id,
                    name : null,
                    type : m_element.type
                }
            };
            ajax_addNode(data,item);

        }
    }
    ,remove: function(item){
        if(window.confirm("Do you really what to delete it")){
            if($(item).parent().children().length === 1){
                treeItem.becomeLeafNode($(item).parent().parent());
            }
            var data = {
                process : 'remove',
                relation : 'is-a',
                source: {
                    id : m_element.id,
                    type : m_element.type
                }
            };
            ajax_removeNode(data,item);
        }
    }
    ,becomeLeafNode : function(item){
        $(item).children("a").removeClass("plus");
        $(item).children("a").removeClass("minus");
    }
    ,getBriefInfo : function(item){
        $("#testTree").find(".active").removeClass("active");
        $(item).addClass("active");

        var unionList = $("#testTree").children("li");
        for(var i= 0;i<unionList.length;i++){
            var count = $(unionList).eq(i).next().find(".active").length;
            if(count === 1){
                m_element.id = $(item).children("input[type='hidden']").val();
                m_element.type = $(unionList).eq(i).text().replace(/(^\s*)|(\s*$)/g, "");
                break;
            }
        }
    }
    ,getDetailInfo : function(item){
        treeItem.getBriefInfo($(item));
        var data = {
            process : 'get',
            relation : '',
            node : {
                id : m_element.id,
                type : m_element.type
            }
        };
        ajax_getNode(data);
    }
    , showDetailInfo :function(node){
        ajax_getHtml("ifm-content",function(html){
            for(var name in node.name)  {break;}
            //content的初始化
            $(".span6-compact.content-detail").html(html);
            $("#ifm-content").children("legend").text(m_element.type.toUpperCase());
            $("#ifm-content").children("#ifm-element-name").children(".control-group").eq(0).find("p").text(name);
            $("#ifm-content").children("#ifm-element-name").children(".control-group").eq(0).find("input[type=text]").val(name);

            $("#rintra-content").children().remove();
            $("#rinter-content").children().remove();
            //rintra的输出
            for(var i=0;i<rintra.length;i++){
                for(var id in node[rintra[i]]){
                    $("#rintra-content").append(getHtml.addRelation(treeItem.searchById(id,m_element.type.toLowerCase()),id,rintra[i]));
                }
            }
            //rinter的输出
            var legalRinter = rinter[m_element.type.toLowerCase()];
            for(var i=0;i<legalRinter.length;i++){
                for(var id in node[legalRinter[i]]){
                    $("#rinter-content").append(getHtml.addRelation(treeItem.searchById(id,m_element.type.toLowerCase()),id,legalRinter[i]));
                }
            }
        });
    }
    ,searchById : function(id,type){
        var count = 0;
        var list = $("#testTree").find("input[type='hidden']");
        for(var i=0;i<list.length;i++){
            if($(list).eq(i).val()===id){
                count++;
                var name = $(list).eq(i).parent().text();
            }
        }
        if(count>1) name=type;
        return name
    }
    ,searchByName : function(name,type){
        var unionList = $("#testTree").children("li");
        //找到类
        if(type != undefined){
            for(var i= 0;i<unionList.length;i++){
                if($(unionList).eq(i).text().replace(/(^\s*)|(\s*$)/g, "").toLowerCase() === type.toLowerCase()){
                    unionList = $(unionList).eq(i);
                    break;
                }
            }
        }
        if(name != undefined){
            //如果和根一致
            if(name.toUpperCase() === $(unionList).text().replace(/(^\s*)|(\s*$)/g, "").toUpperCase()) {
                var id = $(unionList).children("input[type='hidden']").val();
                return id;
            }
            //否则进行查找
            var element = $(unionList).next().find(".element");
            for(var i= 0;i<element.length;i++){
                if($(element).eq(i).text() === name){
                    var id = $(element).eq(i).children("input[type='hidden']").val();
                    return id;
                }
            }
        }
    }
    ,init : function(root,ifm){
        $("#testTree").children("li").next().children().remove();
        for(var i=0;i<collectionList.length;i++){
            var item = $("#testTree").children("li").eq(i);
            if(ifm[collectionList[i]][root] === undefined) continue;
            for(var j=0;j<ifm[collectionList[i]][root].length;j++){
                treeItem.initAppendNode(item,ifm[collectionList[i]][root][j],ifm[collectionList[i]]);
            }
        }
        var minusList = $("#testTree").find(".icon.minus") ;
        for(var i=0;i<minusList.length;i++){
            $(minusList).eq(i).addClass("plus");
            $(minusList).eq(i).removeClass("minus");
            $(minusList).eq(i).parent().children("ul").hide();
        }
        $("#testTree").find(".element").eq(0).click();
    }
    ,initAppendNode : function(item,node,list){
        for(var name in node.name){
            break;
        }
        var html = getHtml.addNode(name, node._id);
        //显示
        var newItem;
        if($(item).hasClass("nav-header")){//顶头情况
            $(item).next().append(html);
            $(item).next().show();
            newItem = $(item).next().children().last();
        }else{//一般情况
            $(item).children("ul").append(html);
            $(item).children("ul").show();
            newItem = $(item).children("ul").children().last();

            $(item).children("a").removeClass("plus");
            $(item).children("a").addClass("minus");
        };
        if(list[node._id] === undefined) return;
        for(var j=0;j<list[node._id].length;j++){
            treeItem.initAppendNode(newItem,list[node._id][j],list);
        }
    }
}

/* 每个选项卡的代码 */
var getHtml = {
    addNode : function(name,id){
        var html = '<li><a class="icon" ></a>' +
            '<div class="element">'+name
            + '<span><i class="icon-zoom-in" title="Expend"></i><i class="icon-plus" title="Add Child"></i><i class="icon-trash" title="Remove"></i></span>'
            + '<input type="hidden" value='+id+'>'
            + '</div>'
            + '<ul style="display: none"></ul>'
        return html;
    }
    ,addRelation : function(name,id,type){
        var html = '<div class="accordion-group">' +
            '<input type="hidden" value='+id+'>' +
                '<div class="accordion-heading" style="color:#000000">' +
                    '<a class="accordion-toggle" style="padding: 0px 0px 0px 0px;">' +
                        '<div class="row row-model" style="margin-left: -20px;">' +
                            '<div class="span5">' +
                                '<label class="control-label-small" style="color:#000000">'+ type+'</label>' +
                                '<p class="controls-text-small get-elem" style="color:#000000">this <strong>' + type +'</strong> <CITE>'+name+'</CITE></p>' +
                            '</div>'+
                            '<div class="span1-compact" style="display:none;">'+
                                '<span class="add-on remove-input" style="margin-left: 0px" ><i class="icon-edit" title="Edit"></i></span>'+
                                '<span class="add-on remove-input" style="margin-left: 5px" ><i class="icon-trash" title="Delete Attri"></i></span>'+
                            '</div>'+
                        '</div>'+
                    '</a>'+
                '</div>'+
            '</div>';
        return html;
    }
}

